package jp.dodododo.dao.util;

import java.beans.Introspector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author Satoshi Kimura
 */
public abstract class StringUtil {
	/**
	 * fooBarBaz -> FOO_BAR_BAZ
	 */
	public static String decamelize(String s) {
		if (s == null) {
			return null;
		}
		if (s.length() == 0) {
			return s;
		}
		int length = s.length();
		StringBuilder buf = new StringBuilder(length);
		for (int i = 0; i < length - 1; i++) {
			if (Character.isLowerCase(s.charAt(i)) && Character.isUpperCase(s.charAt(i + 1))) {
				buf.append(s.charAt(i));
				buf.append('_');
			} else {
				buf.append(s.charAt(i));
			}
		}
		buf.append(s.charAt(length - 1));
		return buf.toString().toUpperCase();
	}

	/**
	 * FOO_BAR_BAZ -> fooBarBaz
	 */
	public static String camelize(String targetStr) {
		Pattern p = Pattern.compile("_([a-z])");
		Matcher m = p.matcher(targetStr.toLowerCase());

		StringBuffer sb = new StringBuffer(targetStr.length());
		while (m.find()) {
			m.appendReplacement(sb, m.group(1).toUpperCase());
		}
		m.appendTail(sb);
		return sb.toString();
	}

	/**
	 * fooBarBaz -> FooBarBaz
	 */
	public static String capitalize(String s) {
		return StringUtils.capitalize(s);
	}

	/**
	 * FooBarBaz -> fooBarBaz
	 */
	public static String decapitalize(String s) {
		return Introspector.decapitalize(s);
	}

	public static String trimLine(String sql) {
		try {
			StringBuffer ret = new StringBuffer();
			BufferedReader bufferedReader = new BufferedReader(new StringReader(sql));
			for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
				if (line.trim().length() != 0) {
					ret.append(line);
					ret.append("\n");
				}
			}
			return ret.toString().trim();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
